package com.bobi.tfca.ui.mainnavigation.home.culture

import android.view.View
import android.widget.ImageView
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.ArticleAPI
import com.bobi.tfca.network.response.ArticleResponse
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.viewmodel.PublicViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class CultureFragmentVM : ViewModel() {

    val articles by lazy {
        MutableLiveData(ArrayList<ArticleResponse>())
    }

    /**
     * 查询所有协会文化文章
     */
    fun findAllArticles(
        publicViewModel: PublicViewModel,
        fragment: CultureFragment,
        noDataIV: ImageView
    ) {
        publicViewModel.apply {
            request(ArticleAPI::class.java).findAllCultures().getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val list = it.data?.data ?: arrayListOf()
                                if (list.size == 0) {
                                    noDataIV.visibility = View.VISIBLE
                                } else {
                                    noDataIV.visibility = View.GONE
                                }
                                articles.value = list
                            }
                        }
                    }
                }
            }
        }
    }
}